package com.rs.lc.pm.utils;

import org.apache.commons.io.Charsets;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.crypto.codec.Base64;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Xavier_Wei on 16/8/11.
 */
public class CookieUtil {

    private static final String persistCookieName = "pm_uid";
    private static final String DELIMITER = ":";

    private static final int DEFAULT_EXPIRY = 1000 * 60 * 60 * 24 * 14;


    public static void setUserCookie(String[] tokens, HttpServletRequest request,
                                     HttpServletResponse response) {
        setUserCookie(tokens, DEFAULT_EXPIRY, request, response);
    }

    public static void setUserCookie(String[] tokens, int maxAge, HttpServletRequest request,
                                     HttpServletResponse response) {
        String cookieValue = encodeCookie(tokens);
        Cookie cookie = new Cookie(persistCookieName, cookieValue);
        cookie.setMaxAge(maxAge);
        cookie.setPath(getCookiePath(request));

        cookie.setSecure(false);
        cookie.setHttpOnly(true);
        cookie.setDomain(request.getServerName());
        response.addCookie(cookie);
    }

    public static void clearUserCookie(HttpServletRequest request,
                                       HttpServletResponse response) {
        Cookie cookie = new Cookie(persistCookieName, null);
        cookie.setMaxAge(0);
        cookie.setPath(getCookiePath(request));
        cookie.setSecure(false);
        cookie.setHttpOnly(true);
        cookie.setDomain(request.getServerName());
        response.addCookie(cookie);
    }

    /**
     * 返回用户的登录String数组
     *
     * @param request
     * @return
     */
    public static String[] getUserCookieDecodeValue(HttpServletRequest request) {
        Cookie cookie = getUserCookie(request);
        if (cookie == null) {
            return null;
        }
        return decodeCookie(cookie.getValue());
    }

    private static Cookie getUserCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (ArrayUtils.isEmpty(cookies)) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (persistCookieName.equals(cookie.getName())) {
                return cookie;
            }
        }
        return null;
    }

    /**
     * Inverse operation of decodeCookie.
     *
     * @param cookieTokens the tokens to be encoded.
     * @return base64 encoding of the tokens concatenated with the ":" delimiter.
     */
    protected static String encodeCookie(String[] cookieTokens) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < cookieTokens.length; i++) {
            sb.append(cookieTokens[i]);
            if (i < cookieTokens.length - 1) {
                sb.append(DELIMITER);
            }
        }
        String value = sb.toString();
        byte[] encodeValue = DES.encrypt(value.getBytes());
        byte[] baseEncodeValue = Base64.encode(encodeValue);
        return new String(baseEncodeValue);
    }


    protected static String[] decodeCookie(String cookieValue) {
        byte[] base64Value = Base64.decode(cookieValue.getBytes());
        String result = null;
        try {
            byte[] desDecode = DES.decrypt(base64Value);
            result = new String(desDecode, Charsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return result.split(DELIMITER);
    }

    private static String getCookiePath(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        return contextPath.length() > 0 ? contextPath : "/";
    }
}
